//
//  LoginViewController.m
//  Ezi2u
//
//  Created by mac on 16/9/18.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "LoginViewController.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import "WXApi.h"
#import "CommonDefines.h"
#import "UIImageView+CreateByUrl.h"
#import "SUCache.h"
#import <AFNetworking.h>
#import "AppDelegate.h"
#import <SVProgressHUD.h>
#import "APIConnection.h"
#import "NSString+MD5.h"
#import "NSString+token.h"
#import "NSString+URL.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initComponents];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(_updateContent:)
                                                 name:FBSDKProfileDidChangeNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(_accessTokenChanged:)
                                                 name:FBSDKAccessTokenDidChangeNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(setWechatUserInfor)
                                                 name:@"weChatLogin"
                                               object:nil];
//    SUCacheItem *item = [SUCache itemForSlot:0];
//    [self labelDisplayWithProfile:item.profile];
}

- (void)labelDisplayWithProfile:(FBSDKProfile *)profile{
    NSInteger slot = 0;
    if (profile) {
        SUCacheItem *cacheItem = [SUCache itemForSlot:slot];
        cacheItem.profile = profile;
        [SUCache saveItem:cacheItem slot:slot];
        NSLog(@"name = %@,userID = %@",cacheItem.profile.name,cacheItem.profile.userID);
        
        NSDictionary *weChatDic = [NSDictionary dictionaryWithObjectsAndKeys:cacheItem.profile.name,@"name",cacheItem.profile.userID, @"userid",nil];
        [[NSUserDefaults standardUserDefaults] setObject:weChatDic forKey:FB_USERINFOR];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [self setFacebookUserInfor];
    }
}

- (void)autoLoginWithToken:(FBSDKAccessToken *)token {
    [FBSDKAccessToken setCurrentAccessToken:token];
    FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields":@"id,name"}];
    [request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
        //token过期，删除存储的token和profile
        if (error) {
            NSLog(@"The user token is no longer valid.");
            NSInteger slot = 0;
            [SUCache deleteItemInSlot:slot];
            [FBSDKAccessToken setCurrentAccessToken:nil];
            [FBSDKProfile setCurrentProfile:nil];
        }
        //做登录完成的操作
        else {
            NSLog(@"name = %@,userID = %@",[FBSDKProfile currentProfile].name,[FBSDKProfile currentProfile].userID);
            
            NSDictionary *weChatDic = [NSDictionary dictionaryWithObjectsAndKeys:[FBSDKProfile currentProfile].name,@"name",[FBSDKProfile currentProfile].userID, @"userid",nil];
            [[NSUserDefaults standardUserDefaults] setObject:weChatDic forKey:FB_USERINFOR];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [self setFacebookUserInfor];
        }
    }];
}

- (void)newLogin {
    FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
    [login
     logInWithReadPermissions: @[@"public_profile", @"email"]
     fromViewController:self
     handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
         NSLog(@"facebook login result.grantedPermissions = %@,error = %@",result.grantedPermissions,error);
         if (error) {
             NSLog(@"Process error");
         } else if (result.isCancelled) {
             NSLog(@"Cancelled");
         } else {
             NSLog(@"Logged in");
             NSLog(@"name = %@,userID = %@",[FBSDKProfile currentProfile].name,[FBSDKProfile currentProfile].userID);
         }
     }];
}

#pragma mark - Notification

- (void)_updateContent:(NSNotification *)notification {
    FBSDKProfile *profile = notification.userInfo[FBSDKProfileChangeNewKey];
    [self labelDisplayWithProfile:profile];
}

- (void)_accessTokenChanged:(NSNotification *)notification
{
    FBSDKAccessToken *token = notification.userInfo[FBSDKAccessTokenChangeNewKey];
    if (!token) {
        [FBSDKAccessToken setCurrentAccessToken:nil];
        [FBSDKProfile setCurrentProfile:nil];
    } else {
        NSInteger slot = 0;
        SUCacheItem *item = [SUCache itemForSlot:slot] ?: [[SUCacheItem alloc] init];
        if (![item.token isEqualToAccessToken:token]) {
            item.token = token;
            [SUCache saveItem:item slot:slot];
        }
    }
}
#pragma mark -login-
- (IBAction)login:(id)sender {

    if([self.usernameTF.text isEqualToString:@""] || self.usernameTF.text == NULL){
        [self alertViewShowOneWithMsg:@"Please input username！"];
        return;
    }
    if([self.passwordTF.text isEqualToString:@""] || self.passwordTF.text == NULL){
        [self alertViewShowOneWithMsg:@"Please input password！"];
        return;
    }
    
    [SVProgressHUD showWithStatus:@"Logging..."];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    NSDictionary *postDic = @{
                              @"username":self.usernameTF.text,
                              @"password":[NSString MD5:self.passwordTF.text]
                              };

    NSString *postUrl = [NSString stringWithFormat:@"iosapp/index.php?mod=app&act=cklogin&token=%@",[NSString MD5:[NSString token]]];
    [[APIConnection shareInstance] post:postUrl data:postDic apiFinish:^(id data, NSString *message) {
        //存储用户名和密码
        [[NSUserDefaults standardUserDefaults] setObject:self.usernameTF.text forKey:EZI2U_USERNAME];
        [[NSUserDefaults standardUserDefaults] setObject:self.passwordTF.text forKey:EZI2U_PASSWORD];
        [self.A_Delegate loginActionWithTag:ActionTypeLogin];
        [self dismissViewControllerAnimated:YES completion:^{
            NSLog(@"dismiss!-->Login!");
        }];
    } netError:^(NSString *errorInfor) {
        [SVProgressHUD showErrorWithStatus:errorInfor];
    }];
}
#pragma mark -forgotPassword-
- (IBAction)forgotPassword:(id)sender {

    [self.A_Delegate loginActionWithTag:ActionTypeForgotPassword];
    [self dismissViewControllerAnimated:YES completion:^{
        NSLog(@"dismiss!-->forgotPassword!");
    }];
}
#pragma mark -registerEzi2u-
- (IBAction)registerEzi2u:(id)sender {
   [self.A_Delegate loginActionWithTag:ActionTypeRegister];
    [self dismissViewControllerAnimated:YES completion:^{
        NSLog(@"dismiss!-->register!");
    }];
}

#pragma mark -facebookLogin-
- (IBAction)facebookLogin:(id)sender {
    NSInteger slot = 0;
    FBSDKAccessToken *token = [SUCache itemForSlot:slot].token;
    if (token) {
        [self autoLoginWithToken:token];
        [SVProgressHUD showWithStatus:@"Logging..."];
        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    }
    else {
        [self newLogin];
    }
}
#pragma mark -wechatLogin-
- (IBAction)wechatLogin:(id)sender {
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:WX_ACCESS_TOKEN];
    NSString *openID = [[NSUserDefaults standardUserDefaults] objectForKey:WX_OPEN_ID];
    // 如果已经请求过微信授权登录，那么考虑用已经得到的access_token
    if (accessToken && openID) {
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
          manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"];
        NSString *refreshToken = [[NSUserDefaults standardUserDefaults] objectForKey:WX_REFRESH_TOKEN];
        NSString *refreshUrlStr = [NSString stringWithFormat:@"%@/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@", WX_BASE_URL, WXAPPId_product, refreshToken];
        [manager GET:refreshUrlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"请求reAccess的response = %@", responseObject);
            NSDictionary *refreshDict = [NSDictionary dictionaryWithDictionary:responseObject];
            NSString *reAccessToken = [refreshDict objectForKey:WX_ACCESS_TOKEN];
            // 如果reAccessToken为空,说明reAccessToken也过期了,反之则没有过期
            if (reAccessToken) {
                // 更新access_token、refresh_token、open_id
                [[NSUserDefaults standardUserDefaults] setObject:reAccessToken forKey:WX_ACCESS_TOKEN];
                [[NSUserDefaults standardUserDefaults] setObject:[refreshDict objectForKey:WX_OPEN_ID] forKey:WX_OPEN_ID];
                [[NSUserDefaults standardUserDefaults] setObject:[refreshDict objectForKey:WX_REFRESH_TOKEN] forKey:WX_REFRESH_TOKEN];
                [[NSUserDefaults standardUserDefaults] synchronize];
                // 当存在reAccessToken不为空时直接执行AppDelegate中的wechatLoginByRequestForUserInfo方法
                AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                [appDelegate wechatLoginByRequestForUserInfo];
            }
            else {
                [self wechatLoginAction];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"用refresh_token来更新accessToken时出错 = %@", error);
        }];
    }
    else {
        [self wechatLoginAction];
    }

}
-(void)wechatLoginAction{
    
    if (![WXApi isWXAppInstalled]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"警告" message:@"请先安装微信客户端！" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
        [alert show];
        return;
    }
    [self sendAuthRequest];
}
#pragma mark -微信第三方登录授权-
-(void)sendAuthRequest{
    SendAuthReq *req = [[SendAuthReq alloc]init];
    req.scope = @"snsapi_userinfo";
    req.state = WXReqState;
    [WXApi sendReq:req];
}

#pragma mark -browse-
- (IBAction)browse:(id)sender {

    [self.A_Delegate loginActionWithTag:ActionTypeAccessLogin];
    [self dismissViewControllerAnimated:YES completion:^{
        NSLog(@"dismiss!-->Only browse!");
    }];
    
}
#pragma mark -allRights-
- (IBAction)allRights:(id)sender {

}
#pragma mark -StatusBarHidden-
-(BOOL)prefersStatusBarHidden{
    return YES;
}
#pragma mark -微信授权之后，用户信息绑定-
-(void)setWechatUserInfor{
    
    [SVProgressHUD showWithStatus:@"Logging..."];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:WX_USERINFOR];
    NSString *postUrl = [NSString stringWithFormat:@"iosapp/index.php?mod=app&act=wechat_cklogin&token=%@&nickname=%@&openid=%@",[NSString MD5:[NSString token]],[dic objectForKey:@"nickname"],[dic objectForKey:@"openid"]];
    postUrl = [postUrl URLEncodedString];
    [[APIConnection shareInstance] post:postUrl data:dic apiFinish:^(id data, NSString *message) {
        
        [self.A_Delegate loginActionWithTag:ActionTypeWeChatLogin];
        [self dismissViewControllerAnimated:YES completion:^{
            NSLog(@"dismiss!-->WeChat_Login!");
        }];
    } netError:^(NSString *errorInfor) {
        [SVProgressHUD showErrorWithStatus:errorInfor];
    }];
}
#pragma mark -Facebook授权之后，用户信息绑定-
-(void)setFacebookUserInfor{
    [SVProgressHUD showWithStatus:@"Logging..."];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:FB_USERINFOR];
    NSString *postUrl = [NSString stringWithFormat:@"iosapp/index.php?mod=app&act=facebook_cklogin&token=%@",[NSString MD5:[NSString token]]];
    [[APIConnection shareInstance] post:postUrl data:dic apiFinish:^(id data, NSString *message) {
        
        [self.A_Delegate loginActionWithTag:ActionTypeFacebookLogin];
        [self dismissViewControllerAnimated:YES completion:^{
            NSLog(@"dismiss!-->Facebook_Login!");
        }];
    } netError:^(NSString *errorInfor) {
        [SVProgressHUD showErrorWithStatus:errorInfor];
    }];
}
#pragma mark -UITextFieldDelegate-
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    if ([textField.text isEqualToString:@""] || textField.text == nil) {
        if ([textField isEqual:_usernameTF]) {
            self.usernameLabel.hidden = YES;
        }else{
            self.passwordLabel.hidden = YES;
        }
    }
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
    if ([textField.text isEqualToString:@""] || textField.text == nil) {
        if ([textField isEqual:_usernameTF]) {
            self.usernameLabel.hidden = NO;
        }else{
            self.passwordLabel.hidden = NO;
        }
    }
}
- (IBAction)editingChanged:(id)sender {
//    UITextField *textField = (UITextField *)sender;
//    if ([textField.text isEqualToString:@""] || textField.text == nil) {
//        if ([textField isEqual:_usernameTF]) {
//            self.usernameLabel.hidden = NO;
//        }else{
//            self.passwordLabel.hidden = NO;
//        }
//    }else{
//        if ([textField isEqual:_usernameTF]) {
//            self.usernameLabel.hidden = YES;
//        }else{
//            self.passwordLabel.hidden = YES;
//        }
//    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    
    return YES;
}

- (void)alertViewShowOneWithMsg:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Warning"
                                                   message:msg
                                                  delegate:nil
                                         cancelButtonTitle:@"OK"
                                         otherButtonTitles:nil];
    [alert show];
}

#pragma mark -初始化控件-
-(void)initComponents{
    
    [self.loginBtn.layer setCornerRadius:22.0];
    [self.browseBtn.layer setCornerRadius:22.0];
    [self.bgdImageView setImage:[UIImage imageNamed:@"bgd.jpg"]];
    [self.bgdImageV setImage:[UIImage imageNamed:@"bgd.jpg"]];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
